﻿using System;
using System.Net;
using System.Text;
using System.Windows;
using eLearning.Model;
using eLearning.Util;
using Microsoft.Phone.Controls;
using Newtonsoft.Json;

namespace eLearning.MahasiswaView
{
    public partial class DashboardPage2 : PhoneApplicationPage
    {
        public DashboardPage2()
        {
            InitializeComponent();
        }

        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            if (SavedUser.Instance.User == null)
                Utility.GotoPage(this, "/Home.xaml");
            else
                GetUserDetail();
        }

        private void GetUserDetail()
        {
            string json = JsonConvert.SerializeObject(SavedUser.Instance.User.ConvertUser());
            Uri uri = new Uri(Config.Instance.MHS_SERVICE_URL() + Config.ACCOUNT_ACTION_KEY, UriKind.Absolute);
            WebClient client = new WebClient();

            client.Encoding = Encoding.UTF8;
            client.Headers[HttpRequestHeader.ContentType] = "application/json";
            client.Headers[HttpRequestHeader.ContentLength] = json.Length.ToString();

            client.UploadStringCompleted += new UploadStringCompletedEventHandler(findUserAccountt_UploadStringCompleted);
            client.UploadStringAsync(uri, "POST", json);
        }

        private void findUserAccountt_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
        {
            try
            {
                MahasiswaList mahasiswas = JsonConvert.DeserializeObject<MahasiswaList>(e.Result);
                SavedUser.Instance.User.Id = mahasiswas[0].Id;
            }
            catch (Exception ex)
            {
                MessageBox.Show("ERROR : " + ex.Message);
            }
        }

        private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
            Utility.GotoPage(this, "/View/LoginPage.xaml");
        }

        private void buttonAccount_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Utility.GotoPage(this, "/View/AccountPage.xaml");
        }

        private void buttonWiki_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Utility.GotoPage(this, "/View/WikiPage.xaml");
        }

        private void buttonKuliah_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            Utility.GotoPage(this, "/View/Mahasiswa/PerkuliahanPage.xaml");
        }
    }
}